import {Component, EventEmitter, Output, Input, ChangeDetectorRef} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams, ToastController, Platform, ItemSliding} from 'ionic-angular';

import {PermissionsService} from "../../../services/native/permissions/permissions.service";
import {ToastService} from '../../../services/common/toast.service';
import {RecorderService} from "../../../services/recorder.service";
import {Voice} from '../../../model/common/page-voice.model';

@Component({
    selector: 'adp-media-audio',
    templateUrl: 'adp-media-audio.html',
    providers: [
        PermissionsService,
        ToastService,
        RecorderService,
    ]
})
export class AdpMediaAudioComponent {
    // 录音成功后的发布订阅
    @Output() audioSuccess:EventEmitter<any>=new EventEmitter();
    // 新增文字跟进
    @Output() addNewProgress:EventEmitter<any>=new EventEmitter();
    // 组件显示状态
    @Input() audioStatus:boolean;
    // 底部按钮类型
    @Input() audioBtn:number;
    // 文字跟进跳转
    @Input() page:any;
    // 文字(1)、语音(2)跟进切换
    private noteType: number = 1;
    // 标记android媒体授权
    private androidPermission:any[]=[];
    // 标记ios授权
    private iosPermisson:boolean;
    // 录音状态
    private isRecording: boolean;
    // 语音时长
    private voiceLength: number;
    // 录音计时器
    private timerHanderSecondId: any;
    // 停止录音计时器
    private timerHandlerId: any;
    // 语音弹窗
    private voiceStatus:boolean=false;
    // 当前语音的id
    private voiceId:any;
    //
    private isiPhoneX = false;
    // touch X
    private touchX:number;
    // touch Y
    private touchY:number;

    constructor(
        private platform:Platform,
        private navCtrl:NavController,
        private permissionsService:PermissionsService,
        private toastService:ToastService,
        private recorderService:RecorderService,
        private ref: ChangeDetectorRef,
    ) {
        this.isiPhoneX = /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375);
        console.log('iphoneX',this.isiPhoneX);
    }

    // 跟进列表中跟进类型按钮切换
    switchType(e, num: number) {
        e.stopPropagation();
        e.preventDefault();
        if (num == 1) {
            this.noteType = 1;
        } else if (num == 2) {
            this.noteType = 2;
        } else {
            this.noteType = 1;
        }
    }

    // 开始录音
    startRecord($event) {
        if (!this.platform.is('cordova')) {
            return false;
        }
        this.stopVoice();
        if (this.platform.is('android')){
            this.permissionsService.checkAndroidAudioPermisson().then(res=>{
                console.log('res1', res);
                this.androidPermission=res;
                if(this.androidPermission.length > 0 && this.androidPermission[0] && this.androidPermission[1]){
                    this.recording();
                    console.log(window);
                }else{
                    // console.log(window);
                    // this.permissionsService.getAndroidMicPermisson().then(res=>{
                    //     if(res!='authorized'){
                    //         this.toastService.showToast('请到“设置>应用”中启用“麦克风”和“存储”权限')
                    //     }
                    // }).catch(err=>{
                    //     this.toastService.showToast('请到“设置>应用”中启用“麦克风”和“存储”权限')
                    // });

                    this.toastService.showToast('请到“设置>应用”中启用“麦克风”和“存储”权限');
                    return;
                }
            })
        }else{
            this.permissionsService.checkIosAudioPermisson().then(res=>{
                this.iosPermisson=res;
                if(this.iosPermisson){
                    this.recording();
                }else{
                    // this.permissionsService.getIosMicPermisson().then(res=>{
                    //     if(res!='authorized'){
                    //         this.toastService.showToast('请到"设置-隐私-麦克风”选项中，允许访问你的手机麦克风')
                    //     }
                    // }).catch(err=>{
                    //     this.toastService.showToast('请到"设置-隐私-麦克风”选项中，允许访问你的手机麦克风')
                    // });

                    this.toastService.showToast('请到"设置-隐私-麦克风”选项中，允许访问你的手机麦克风');
                    return;
                }
            })
        }
    }

    // 执行录音
    recording(){
        this.recorderService.releasePlay();
        this.voiceStatus=true;
        this.voiceLength = 0;
        this.isRecording = true;
        this.timerHanderSecondId = setInterval(handler => {
            this.ref.detectChanges();
            this.voiceLength++;
            if(this.voiceLength>=60){
                this.toastService.showToast('录音时长不能超过60秒');
                this.voiceLength=60;
                this.stopRecord(null);
                clearInterval(this.timerHanderSecondId);
            }
        }, 1000);

        this.timerHandlerId = setTimeout(() => {
            /*if(this.voiceLength>=60){
                this.toastService.showToast('录音时长不能超过60s');
            }
            this.voiceLength=60;
            this.stopRecord(null);*/
        }, 60000);
        this.recorderService.startRecorder();
    }

    // 停止录音
    stopRecord($event) {
        if (!this.isRecording) {
            return;
        }
        this.isRecording = false;
        clearTimeout(this.timerHandlerId);
        clearInterval(this.timerHanderSecondId);

        if (this.voiceLength < 1) {
            this.toastService.showToast('录音时间太短');
            this.voiceLength=0;
            this.voiceStatus=false;
            return;
        }
        let fileUrl='';
        if (this.platform.is('cordova')) {
            fileUrl=this.recorderService.stopRecorder();
        }
        if(fileUrl){
            let voice:Voice=new Voice();
            voice.voiceUrl=fileUrl;
            voice.voiceLength=this.voiceLength;
            this.audioSuccess.emit(voice);
        }else{
            this.toastService.showToast('录音数据错误')
        }
        this.voiceStatus=false;
    }

    // 停止播放音频
    stopVoice(){
        this.recorderService.stopPlay();
        this.recorderService.pausePlay();
        this.recorderService.releasePlay();
        this.voiceId=null;
    }

    // 文字跟进跳转
    goToEdit(page){
        this.addNewProgress.emit();
    }

    // touchstart
    touchstart($event){
        let touch=$event.targetTouches[0];
        touch.pageX>=0?this.touchX=touch.pageX:null;
        touch.pageY>=0?this.touchY=touch.pageY:null;
    }

    // touchwindow
    touchmove($event){
        console.log($event);
        let touch=$event.targetTouches[0];
        let valueX=Math.abs(touch.pageX-this.touchX);
        let valueY=Math.abs(touch.pageY-this.touchY);
        if(this.voiceStatus&&valueY>=window['innerWidth'] / 100 * 10){
            this.stopRecord(null);
            this.touchX=0;
            this.touchY=0;
        }
    }

    // touchcancel
    touchcancel($event){
        if(this.voiceLength<=2&&!this.isiPhoneX){
            this.voiceLength=0;
        }
        this.stopRecord(null);
    }
}
